<?php
/*
 * UserApi for auth
 * @author    Leo
 * @filename UserApi.php
 * @Created  2015/7/25 20:10
 */
namespace App\Repositories\User;

use Illuminate\Support\Facades\Auth;
use App\Events\User\UserLogin;

class UserApi {

	public $authError;

	private $user;

	public function __construct(UserRepository $user) {
		$this->user = $user;
	}

	public function login($request) {
		$data = $request->only('authKey', 'password', 'remember');

		if ($user = $this->user->findBy('name', $data['authKey'])) {
			//name 登录
			$auth['name'] = $data['authKey'];
		} elseif ($user = $this->user->findBy('email', $data['authKey'])) {
			//email  登录
			$auth['email'] = $data['authKey'];
		} elseif ($user = $this->user->findBy('mobile', $data['authKey'])) {
			//mobile  登录
			$auth['mobile'] = $data['authKey'];
		} else {
			$this->authError = '账号不存在';
			return false;
		}


		if ($user->locked != 0) {
			$this->authError = '此账号已被禁用';
			return false;
		}

		$auth['password'] = $data['password'];
		$remember         = boolval($data['remember']);

		if (Auth::attempt($auth, $remember)) {
			//触发用户登录事件
			event(new UserLogin(Auth::user()));
			return true;
		}

		$this->authError = '账号或密码错误';
		return false;
	}

	/**
	 * 通过id登录用户
	 * @param $id
	 */
	public function loginById($id) {
		Auth::loginUsingId($id);
		//触发用户登录事件
		event(new UserLogin(Auth::user()));
	}

	/**
	 * 注销用户
	 */
	public function logout() {
		Auth::logout();
	}
}
